// app/edit-scene/[id].tsx

import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Pressable, View, Text, StyleSheet, ScrollView, TextInput, TouchableOpacity, Image, ActivityIndicator, Alert, Button } from 'react-native';
import { Stack, useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import DeviceCard from '@/components/features/device/DeviceCard';
import ButtonDemo from '@/components/features/device/ButtonDemo';
import TimePicker from '@/components/common/TimePicker';
import SelectDeviceCard from '@/components/features/device/SelectDeviceCard';
import { addSceneDevice } from '../../api/scene';
import { getDeviceDetails, getDevices } from '../../api/device';
import getDeviceImage from '../../api/getDeviceImage';
import { deviceTypeEnToZhMap  } from '@/constants/deviceParameters';
import { getRecommendations } from '@/api/recommendation';
import { setSceneTriggers, SetTriggerRequest } from '../../api/scene';

// 导入 Scene、getSceneDetails 和 updateScene
import { Scene as ApiSceneType, getSceneDetails, updateScene, UpdateSceneData, GetAllScenesResponse, removeSceneDevice } from '../../api/scene';
// import { DeviceData } from '@/api/device';

// 定义 SceneDevice 类型接口
interface SceneDevice {
  deviceld: number;
  deviceName: string;
  params: {
    is_on?: boolean;
    mode?: string;
    target_temp?: number;
    fan_speed?: string;
    swing_mode?: string;
    temperature?: number;
    [key: string]: any; // 允许其他参数
  };
}

interface DeviceData {
    id: number;
    name: string;
    type: string;
    family: string;
    meta?: Record<string, any>;
    state: Record<string, any>;    
}

const StepperButton = ({ text, onPress }: { text: string, onPress: () => void }) => (
  <TouchableOpacity onPress={onPress} style={styles.stepperButton}>
    <Text style={styles.stepperButtonText}>{text}</Text>
  </TouchableOpacity>
);

export default function EditScenePage() {
  const { id } = useLocalSearchParams();
  const router = useRouter();
  const sceneId = typeof id === 'string' ? parseInt(id, 10) : undefined;

  const [sceneName, setSceneName] = useState('');
  const [sceneDescription, setSceneDescription] = useState('');
  const [sceneEnabled, setSceneEnabled] = useState(true);
  const [scenePriority, setScenePriority] = useState(0);
  const [triggerValue, setTriggerValue] = useState(25);
  const [triggerTime, setTriggerTime] = useState('07:00');
  const [devices, setDevices] = useState<SceneDevice[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deviceInfoMap, setDeviceInfoMap] = useState<{ [id: number]: { name: string; type: string } }>({});
  const [deviceList, setDeviceList] = useState<DeviceData[]>([]);
  const [isDeleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deviceToDelete, setDeviceToDelete] = useState<number | null>(null);

  // 添加设备到场景的函数


  // 删除设备的函数
  // const handleRemoveDevice = useCallback((deviceId: number) => {
  //   if (sceneId === undefined) {
  //     alert('场景 ID 无效，无法删除设备');
  //     return;
  //   }
  //   try {
  //     removeSceneDevice(sceneId, deviceId);
  //     setDeviceList((prevList) => prevList.filter((device) => device.id !== deviceId));
  //     fetchSceneDetails(); // 刷新场景详情
  //   } catch (error) {
  //     console.error('Error deleting device:', error);
  //   }
  // }, [sceneId]);

  const fetchDeviceList = async () => { 
      try {
          const response = await getDevices();
          const deviceList = response.data.data.devices;
          setDeviceList(deviceList);
          setDeviceList(Array.isArray(deviceList) ? deviceList : []);
      } catch (error) { 
          console.error('Get devices error:', error);
      }
  };

  // 编辑设备参数的函数
  const handleEditDevice = useCallback((device: SceneDevice) => {
      // 安全检查，确保 sceneId 有效
      if (sceneId === undefined) {
          Alert.alert('错误', '场景 ID 无效，无法编辑设备');
          return;
      }

      // 直接跳转到通用的设备编辑页面
      router.push({
          pathname: '/EditSceneDevice/[id]',
          params: {
              id: device.deviceld.toString(),
              deviceType: (device as any).deviceType, // 传递设备类型
              sceneId: sceneId.toString(),           // 传递场景ID
              data: JSON.stringify(device), // 传递设备参数（序列化为字符串）
          }
      });
  }, [router, sceneId]); // 注意：依赖项中需要加入 sceneId

  // 获取场景详情的函数
  const fetchSceneDetails = useCallback(async () => {
    if (sceneId === undefined || isNaN(sceneId)) {
      setError('场景ID无效。');
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const response = await getSceneDetails(sceneId);
      if (response.data.ok) {
        const sceneData = response.data.data;
        setSceneName(sceneData.name);
        setSceneDescription(sceneData.description || '');
        setSceneEnabled(sceneData.enabled !== undefined ? sceneData.enabled : true);
        setScenePriority(sceneData.priority || 0);
        
        if (sceneData.triggers && Array.isArray(sceneData.triggers)) {
          const timeTrigger = sceneData.triggers.find(
            (t: any) => t.type === 'time' && t.config && t.config.trigger_time
          );
          if (timeTrigger) {
            setTriggerTime(timeTrigger.config.trigger_time);
          }
        }

        // 1. 取出所有 device_id
        const actions = sceneData.actions || [];
        const deviceIds = actions.map((a: any) => a.device_id);

        // 2. 批量请求设备详情
        const deviceDetailResults = await Promise.all(
          deviceIds.map((id: number) =>
            getDeviceDetails(String(id))
              .then(res => ({
                id,
                name: res.data.data.name,
                type: res.data.data.type,
              }))
              .catch(() => ({
                id,
                name: '未知设备',
                type: '',
              }))
          )
        );
        // 3. 构建 id->详情 的映射
        const infoMap: { [id: number]: { name: string; type: string } } = {};
        interface DeviceDetailResult {
          id: number;
          name: string;
          type: string;
        }

        interface DeviceInfoMap {
          [id: number]: { name: string; type: string };
        }

        (deviceDetailResults as DeviceDetailResult[]).forEach((data: DeviceDetailResult) => {
          (infoMap as DeviceInfoMap)[data.id] = { name: data.name, type: data.type };
        });
        setDeviceInfoMap(infoMap);

        // 确保设备数据符合 SceneDevice 接口
        const deviceList: SceneDevice[] = (sceneData.actions || []).map((action: any) => ({
          deviceld: action.device_id,
          deviceName: infoMap[action.device_id]?.name || '未知设备',
          deviceType: infoMap[action.device_id]?.type || '',
          params: action.command || {},
        }));
        
        setDevices(deviceList);
      } else {
        const errorMsg = (response.data as any).error?.message || '获取场景详情失败。';
        setError(errorMsg);
        Alert.alert('错误', errorMsg);
      }
    } catch (err: any) {
      console.error('Failed to fetch scene details:', err.response?.data || err.message);
      setError('无法加载场景详情，请稍后再试。');
      Alert.alert('错误', `无法加载场景详情: ${err.response?.data?.error?.message || err.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  }, [sceneId]);

  // 保存场景信息的函数（包含设备信息）
  // ...existing code...

const handleSaveScene = useCallback(async () => {
  if (sceneId === undefined || isNaN(sceneId)) {
    Alert.alert('错误', '场景ID无效');
    return;
  }

  if (!sceneName.trim()) {
    Alert.alert('错误', '场景名称不能为空');
    return;
  }

  setSaving(true);
  try {
    const updateData: UpdateSceneData = {
      name: sceneName.trim(),
      description: sceneDescription.trim() || undefined,
      enabled: sceneEnabled,
      priority: scenePriority,
    };

    // 1. 先保存场景基本信息
    const response = await updateScene(sceneId, updateData);

    // 2. 再设置触发时间（如果有）
    if (triggerTime) {
      const triggerPayload: SetTriggerRequest = {
        type: 'time',
        config: { trigger_time: triggerTime }
      };
      await setSceneTriggers(sceneId, triggerPayload);
    }

    if (response.data.ok) {
      Alert.alert(
        '成功', 
        '场景信息已保存',
        [
          {
            text: '确定',
            onPress: () => {
              fetchSceneDetails();
            }
          }
        ]
      );
    } else {
      const errorMsg = (response.data as any).error?.message || '保存失败';
      Alert.alert('错误', errorMsg);
    }
  } catch (err: any) {
    console.error('Failed to save scene:', err.response?.data || err.message);
    const errorMsg = err.response?.data?.error?.message || err.message || '保存失败，请稍后再试';
    Alert.alert('错误', errorMsg);
  } finally {
    setSaving(false);
  }
}, [sceneId, sceneName, sceneDescription, sceneEnabled, scenePriority, triggerTime, fetchSceneDetails]);

// ...existing code...

  // 组件加载时获取场景详情
  useEffect(() => {
    fetchSceneDetails();
    fetchDeviceList();
  }, [fetchSceneDetails]);

  useFocusEffect(
      React.useCallback(() => {
          fetchSceneDetails();
      }, [])
  );

  // 将从API获取的设备和"添加设备"卡片组合

const combinedDeviceItems = [
  ...devices
    .filter(device => device && device.deviceld != null)
    .map(device => {
    const englishType = (device as any).deviceType || '';
    const chineseType = deviceTypeEnToZhMap[englishType] || englishType;
    return {
      id: device.deviceld.toString(), 
      title: device.deviceName,
      desc: chineseType,
      image: getDeviceImage(englishType),
      device: device 
    };
    }),
  { id: 'add_device_card', title: '', desc: '', image: '', device: null }
];

  if (loading) {
    return (
      <View style={styles.centered}>
        <ActivityIndicator size="large" color="#0000ff" />
        <Text>加载场景详情中...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.centered}>
        <Text style={styles.errorText}>{error}</Text>
        <Button title="重试" onPress={fetchSceneDetails} />
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#fff'}}>
      <ScrollView style={{ flex: 1 }}>
        <View style={styles.headerContainer}>
          <Stack.Screen options={{ headerShown: false }} />
        <Image
          source={require('../../assets/images/familyBackground.png')}
          style={styles.headerBackgroundImage}
        />
        <View style={styles.headerTextContainer}>
          <Text style={styles.headerTitle}>{sceneName || '加载中...'}</Text>
          <Text style={styles.headerSubtitle}>编辑场景</Text>
        </View>
      </View>

        <View style={styles.contentContainer}>
          <View style={styles.section}>
            <Text style={styles.label}>场景名称</Text>
            <TextInput 
              style={styles.input} 
              value={sceneName} 
              onChangeText={setSceneName} 
              placeholder="请输入场景名称" 
              editable={!saving}
            />
          </View>

          {/* <View style={styles.section}>
            <Text style={styles.label}>场景描述</Text>
            <TextInput 
              style={[styles.input, styles.textArea]} 
              value={sceneDescription} 
              onChangeText={setSceneDescription} 
              placeholder="请输入场景描述（可选）" 
              multiline={true}
              numberOfLines={3}
              editable={!saving}
            />
          </View> */}

        <View style={styles.section}>
          <Text style={styles.label}>场景设置</Text>
          <View style={styles.settingRow}>
            <Text style={styles.settingLabel}>启用场景</Text>
            <TouchableOpacity 
              style={[styles.switch, sceneEnabled && styles.switchActive]}
              onPress={() => !saving && setSceneEnabled(!sceneEnabled)}
              disabled={saving}
            >
              <View style={[styles.switchThumb, sceneEnabled && styles.switchThumbActive]} />
            </TouchableOpacity>
          </View>
          <View style={styles.settingRow}>
            <Text style={styles.settingLabel}>优先级</Text>
            <View style={styles.stepper}>
              <StepperButton 
                text="-" 
                onPress={() => !saving && setScenePriority(v => Math.max(0, v - 1))} 
              />
              <Text style={styles.stepperValue}>{scenePriority}</Text>
              <StepperButton 
                text="+" 
                onPress={() => !saving && setScenePriority(v => v + 1)} 
              />
            </View>
          </View>
          <View style={styles.settingRow}>
            <Text style={styles.settingLabel}>触发时间</Text>
            <TimePicker 
              value={triggerTime}
              onChange={setTriggerTime}  // 现在接收的是字符串 '07:00'
              placeholder="不使用时间触发"
              disabled={saving}
            />
          </View>
        </View>

        {/* <View style={styles.section}> */}
          {/* <Text style={styles.label}>触发条件</Text> */}
          {/* <View style={styles.triggerTable}>
              <View style={styles.triggerTableHeader}>
                  <Text style={styles.triggerHeaderText}>触发方式</Text>
                  <Text style={styles.triggerHeaderText}>详细触发信息</Text>
              </View> */}
              {/* <View style={styles.triggerTableRow}>
                  <View style={styles.triggerTableCell}>
                      <Text style={styles.contentText}>温度</Text>
                  </View>
                  <View style={styles.triggerTableCell}>
                      <View style={styles.stepper}>
                          <StepperButton text="-" onPress={() => setTriggerValue(v => v - 1)} />
                          <Text style={styles.stepperValue}>{triggerValue}</Text>
                          <StepperButton text="+" onPress={() => setTriggerValue(v => v + 1)} />
                      </View>
                  </View>
              </View> */}

            {/* 时间触发行 */}
              {/* <View style={styles.triggerTableRow}>
                  <View style={styles.triggerTableCell}>
                    <Text style={styles.contentText}>时间</Text>
                  </View>
                  <View style={styles.triggerTableCell}>
                    <TimePicker 
                      value={triggerTime}
                      onChange={setTriggerTime}  // 现在接收的是字符串 '07:00'
                      placeholder="不使用时间触发"
                    />
                  </View>
                </View> */}
              
          {/* </View> */}
        {/* </View> */}
        
        <View style={styles.section}>
          <Text style={styles.label}>场景规则 ({devices.length} 个设备)</Text>
          <View style={styles.gridContainer}>
            {Array.from({ length: Math.ceil(combinedDeviceItems.length / 2) }).map((_, rowIndex) => (
              <View key={rowIndex} style={styles.gridRow}>
                {combinedDeviceItems.slice(rowIndex * 2, rowIndex * 2 + 2).map((item) => (
                  <View key={item.id} style={styles.gridColumn}>
                    {item.id === 'add_device_card' ? (
                      <SelectDeviceCard
                        onDeviceSelect={async (deviceId) => {
                          if (!sceneId) return;
                          try {
                            // 从 deviceList 中找到选中的设备对象
                            const selectedDevice = deviceList.find(dev => dev.id === Number(deviceId));
                            if (!selectedDevice) {
                              alert('未找到该设备');
                              return;
                            }
                            // 跳转到对应设备编辑页面，传递 id 和 type
                            await addSceneDevice(sceneId, Number(deviceId));
                            router.push({
                              pathname: '/EditSceneDevice/[id]',
                              params: { id: selectedDevice.id.toString(), deviceType: (selectedDevice as DeviceData).type, sceneId: sceneId.toString() }
                            });
                            // 如需刷新场景详情可保留
                            fetchSceneDetails();
                          } catch (e) {
                            alert('添加设备失败');
                          }
                        }}
                      />
                    ) : (
                      <DeviceCard
                        title={item.title}
                        desc={item.desc}
                        image={item.image}
                        onPress={() => handleEditDevice(item.device!)}
                        onLongPress={() => {
                          setDeviceToDelete(id ? Number(item.id) : null);
                          setDeleteModalVisible(true);
                        }}
                      />
                    )}
                  </View>
                ))}
                {combinedDeviceItems.slice(rowIndex * 2, rowIndex * 2 + 2).length === 1 && (
                  <View style={styles.gridColumn} />
                )}
              </View>
            ))}
          </View>
        </View>

          <View style={styles.footer}>
            {/* <View style={styles.footerButtonWrapper}>
              <ButtonDemo 
                text="重置" 
                onPress={() => {
                  Alert.alert(
                    '确认重置',
                    '确定要重置所有更改吗？',
                    [
                      { text: '取消', style: 'cancel' },
                      {
                        text: '重置',
                        style: 'destructive',
                        onPress: fetchSceneDetails
                      }
                    ]
                  );
                }} 
              />
            </View> */}
            <View style={styles.footerButtonWrapper}>
              <ButtonDemo 
                text={saving ? "保存中..." : "保存"} 
                onPress={handleSaveScene}
              />
            </View>
          </View>
        </View>
        <Modal
            animationType="fade"
            transparent={true}
            visible={isDeleteModalVisible}
            onRequestClose={() => setDeleteModalVisible(false)}
        >
            <View style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: 'rgba(0,0,0,0.5)',
            }}>
                <View style={{
                    width: 300,
                    padding: 20,
                    backgroundColor: 'white',
                    borderRadius: 10,
                    alignItems: 'center',
                }}>
                    <Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 10 }}>
                        确认删除
                    </Text>
                    <Text>
                        确定要删除设备吗？
                    </Text>
                    <View style={{ flexDirection: 'row', marginTop: 20 }}>
                        <Pressable
                            style={{
                                padding: 10,
                                marginRight: 10,
                                backgroundColor: '#ccc',
                                borderRadius: 5,
                            }}
                            onPress={() => setDeleteModalVisible(false)}
                        >
                            <Text>取消</Text>
                        </Pressable>
                        <Pressable
                            style={{
                                padding: 10,
                                backgroundColor: 'red',
                                borderRadius: 5,
                            }}
                            onPress={async () => {
                                if (deviceToDelete) {
                                  // handleRemoveDevice(deviceToDelete.id); // 调用删除函数
                                  await removeSceneDevice(sceneId!, deviceToDelete); // 调用删除接口
                                }
                                setDeleteModalVisible(false); // 关闭弹窗
                                fetchSceneDetails(); // 刷新场景详情
                            }}
                        >
                            <Text style={{ color: 'white' }}>删除</Text>
                        </Pressable>
                    </View>
                </View>
            </View>
        </Modal>
      </ScrollView>
    </View>
  );
}

// 样式
const styles = StyleSheet.create({
  headerContainer: { width: '100%', height: 180, position: 'relative', justifyContent: 'center', alignItems: 'center' },
  headerBackgroundImage: { ...StyleSheet.absoluteFillObject, width: undefined, height: undefined },
  headerTextContainer: { backgroundColor: 'rgba(0,0,0,0.3)', padding: 20, borderRadius: 10, alignItems: 'center' },
  headerTitle: { fontSize: 32, fontWeight: 'bold', color: '#fff', textShadowColor: 'rgba(0, 0, 0, 0.75)', textShadowOffset: {width: -1, height: 1}, textShadowRadius: 10 },
  headerSubtitle: { fontSize: 16, color: '#fff', marginTop: 8 },
  contentContainer: {},
  section: { backgroundColor: '#fff', padding: 20, marginTop: 12 },
  label: { fontSize: 18, fontWeight: 'bold', marginBottom: 15 },
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 10, fontSize: 16 },
  textArea: { height: 80, textAlignVertical: 'top' },
  contentText: { fontSize: 16 },
  gridContainer: {},
  gridRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 16 },
  gridColumn: { width: '48%' },
  triggerTable: { borderWidth: 1, borderColor: '#eee', borderRadius: 8 },
  triggerTableHeader: { flexDirection: 'row', backgroundColor: '#f8f9fa', paddingVertical: 8 },
  triggerHeaderText: { flex: 1, textAlign: 'center', fontWeight: 'bold', color: '#666' },
  triggerTableRow: { flexDirection: 'row', borderTopWidth: 1, borderTopColor: '#eee' },
  triggerTableCell: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 10, minHeight: 50 },
  stepper: { flexDirection: 'row', alignItems: 'center' },
  stepperValue: { fontSize: 16, fontWeight: 'bold', marginHorizontal: 15 },
  stepperButton: { width: 30, height: 30, borderRadius: 15, backgroundColor: '#eef2ff', justifyContent: 'center', alignItems: 'center' },
  stepperButtonText: { color: '#4338cc', fontSize: 18, fontWeight: 'bold' },

  settingRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  settingLabel: {
    fontSize: 16,
    color: '#333',
  },
  switch: {
    width: 50,
    height: 28,
    borderRadius: 14,
    backgroundColor: '#ccc',
    justifyContent: 'center',
    paddingHorizontal: 2,
  },
  switchActive: {
    backgroundColor: '#4338cc',
  },
  switchThumb: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: '#fff',
    alignSelf: 'flex-start',
  },
  switchThumbActive: {
    alignSelf: 'flex-end',
  },

  footer: {
    flexDirection: 'column',
    justifyContent: 'space-between',
    paddingLeft: 17,
    marginTop: 20,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0',
    // alignItems: 'center',
  },
  footerButtonWrapper: {
    // width: '100%',
    borderTopWidth: 0,
    alignItems: 'center',
  },
  centered: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    minHeight: 200,
  },
  errorText: {
    color: 'red',
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 10,
  },
});